package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONObject;

public class ModifyPswActivity extends BaseActivity implements View.OnClickListener {
    private final static String TAG = "ModifyPswActivity";
    private TextView tv_aboutus;
    //private EditText et_oldpass;
    private EditText et_new_password;
    private EditText et_conf_password;
    private Button b_submit;
    private Context mContext;
    CommonLoading loading;
    LinearLayout title_reback;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rest_password);
        mContext = this;
        tv_aboutus = (TextView) findViewById(R.id.title_text);
        tv_aboutus.setText("修改密码");
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);
        //et_oldpass = (EditText) findViewById(R.id.et_oldpass);
        et_new_password = (EditText) findViewById(R.id.et_new_password);
        et_conf_password = (EditText) findViewById(R.id.et_conf_password);
        b_submit = (Button) findViewById(R.id.b_submit);
        b_submit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.b_submit:
                checkModify();
                break;
            case R.id.title_reback:
                finish();
                break;
             default:
                 break;
        }
    }

    private void checkModify() {
       /* if (StringUtil.isEmpty(et_oldpass.getText().toString())) {
            ToastUtils.showShort(mContext, "请输入旧密码");
            return;
        }*/
        if (StringUtil.isEmpty(et_new_password.getText().toString())) {
            ToastUtils.showShort(mContext, "请输入新密码");
            return;
        }
        if (StringUtil.isEmpty(et_conf_password.getText().toString())) {
            ToastUtils.showShort(mContext, "请输入确认密码");
            return;
        }
        Utils.hintKeyboard(mContext);
        if(et_new_password.getText().toString().equals(et_conf_password.getText().toString())) {
            check(et_new_password.getText().toString());
        } else {
            ToastUtils.showShort(mContext, "输入密码不一致");
        }
    }

    private void check(final String newPs) {
        try {
            String url = NetUtils.USER_PSW;
            loading = new CommonLoading(this);
            loading.setLoadText("修改中...");
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            /*PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
            client.setCookieStore(myCookieStore);*/
            JSONObject jsonObject = new JSONObject();
            if(SharedPreference.getPreferString("type").equals("10")) {
                jsonObject.put("id", SharedPreference.getPreferString("dealer") + "_" + SharedPreference.getPreferString("id"));
                jsonObject.put("dealer", SharedPreference.getPreferString("dealer"));
                jsonObject.put("name", SharedPreference.getPreferString("name"));
                jsonObject.put("type", 10);
                jsonObject.put("disabled", 1);
                jsonObject.put("password", newPs);
            }else if(SharedPreference.getPreferString("type").equals("20")){
                jsonObject.put("id", SharedPreference.getPreferString("id"));
                jsonObject.put("password", newPs);
            }
            ByteArrayEntity stringEntity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
            stringEntity.setContentType("application/json");
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            client.put(mContext, url, stringEntity, "application/json",  new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码14                         if(statusCode == 200){
                    //获取结果
                    loading.dismiss();
                    try {
                        String result = new String(responseBody, "utf-8");
                        Log.d(TAG, "result " + result);
                        JSONObject user = new JSONObject(result);
                        if (user.getInt("status") == 200) {
                            //JSONObject data = user.getJSONObject("data");
                            //Log.d(TAG, "data " + data.toString());
                            SharedPreference.setPreferString("password", newPs);
                            sendMessagea(UPLOAD_SUCCESS, result);
                        } else{
                            sendMessagea(UPLOAD_FAIL, "修改异常");
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        sendMessagea(UPLOAD_FAIL, "修改异常");
                    }
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                    loading.dismiss();
                    sendMessagea(UPLOAD_FAIL, "修改异常");
                    throwable.printStackTrace();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    closeKeyboard();
                    ToastUtils.show("修改成功");
                    finish();
                    break;
                case UPLOAD_FAIL:
                    ToastUtils.show("修改失败，请重新尝试");
                    break;
                default:
                    break;
            }
        }
    };

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

    public void closeKeyboard() {
        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}


